package com.accelstack.cmp.controller;

import com.accelstack.cmp.dto.ServerWithComponentsRequest;
import com.accelstack.cmp.entity.Server;
import com.accelstack.cmp.enums.ServerStatus;
import com.accelstack.cmp.service.ServerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 服务器/主机管理控制器
 */
@Tag(name = "服务器管理", description = "服务器/主机的增删改查接口")
@RestController
@RequestMapping("/api/servers")
@RequiredArgsConstructor
public class ServerController {
    
    private final ServerService serverService;
    
    @Operation(summary = "创建服务器", description = "创建一个新的服务器")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @PostMapping
    public ResponseEntity<Server> create(@Valid @RequestBody Server server) {
        server.setCreatedAt(new Date());
        Server created = serverService.create(server);
        return ResponseEntity.ok(created);
    }
    
    @Operation(summary = "创建服务器（包含硬件组件）", 
               description = "创建一个新的服务器，同时创建CPU、内存、磁盘、网卡和GPU等硬件组件")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @PostMapping("/with-components")
    public ResponseEntity<Server> createWithComponents(@Valid @RequestBody ServerWithComponentsRequest request) {
        Server created = serverService.createWithComponents(request);
        return ResponseEntity.ok(created);
    }
    
    @Operation(summary = "更新服务器", description = "更新现有服务器的信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "404", description = "服务器不存在")
    })
    @PutMapping("/{id}")
    public ResponseEntity<Server> update(
            @Parameter(description = "服务器ID", required = true) @PathVariable Long id,
            @Valid @RequestBody Server server) {
        return serverService.findById(id)
                .map(existing -> {
                    server.setId(id);
                    server.setCreatedAt(existing.getCreatedAt());
                    server.setUpdatedAt(new Date());
                    Server updated = serverService.update(server);
                    return ResponseEntity.ok(updated);
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "删除服务器", description = "根据ID删除服务器")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "服务器不存在")
    })
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(
            @Parameter(description = "服务器ID", required = true) @PathVariable Long id) {
        return serverService.findById(id)
                .map(server -> {
                    serverService.deleteById(id);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "查询服务器详情", description = "根据ID查询服务器的详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<Server> getById(
            @Parameter(description = "服务器ID", required = true) @PathVariable Long id) {
        return serverService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "查询服务器详情（包含关联信息）", description = "根据ID查询服务器及其关联的数据中心和机架信息")
    @GetMapping("/{id}/with-relations")
    public ResponseEntity<Server> getByIdWithRelations(
            @Parameter(description = "服务器ID", required = true) @PathVariable Long id) {
        Server server = serverService.findByIdWithRelations(id);
        if (server != null) {
            return ResponseEntity.ok(server);
        }
        return ResponseEntity.notFound().build();
    }
    
    @Operation(summary = "查询所有服务器", description = "查询系统中所有的服务器列表")
    @GetMapping
    public ResponseEntity<List<Server>> getAll() {
        return ResponseEntity.ok(serverService.findAll());
    }
    
    @Operation(summary = "分页查询服务器", description = "分页查询服务器列表")
    @GetMapping("/page")
    public ResponseEntity<Page<Server>> getPage(
            @PageableDefault(size = 20, sort = "id") Pageable pageable) {
        return ResponseEntity.ok(serverService.findAll(pageable));
    }
    
    @Operation(summary = "根据数据中心查询服务器", description = "查询指定数据中心下的所有服务器")
    @GetMapping("/datacenter/{datacenterId}")
    public ResponseEntity<List<Server>> getByDatacenterId(
            @Parameter(description = "数据中心ID", required = true) @PathVariable Long datacenterId) {
        List<Server> servers = serverService.findByDatacenterId(datacenterId);
        return ResponseEntity.ok(servers);
    }
    
    @Operation(summary = "根据机架查询服务器", description = "查询指定机架中的所有服务器")
    @GetMapping("/rack/{rackId}")
    public ResponseEntity<List<Server>> getByRackId(
            @Parameter(description = "机架ID", required = true) @PathVariable Long rackId) {
        List<Server> servers = serverService.findByRackId(rackId);
        return ResponseEntity.ok(servers);
    }
    
    @Operation(summary = "根据状态查询服务器", description = "查询指定状态的服务器列表")
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Server>> getByStatus(
            @Parameter(description = "服务器状态", required = true) @PathVariable ServerStatus status) {
        List<Server> servers = serverService.findByStatus(status);
        return ResponseEntity.ok(servers);
    }
    
    @Operation(summary = "批量创建服务器", description = "批量创建多个服务器")
    @PostMapping("/batch")
    public ResponseEntity<List<Server>> batchCreate(@Valid @RequestBody List<Server> servers) {
        Date now = new Date();
        servers.forEach(server -> server.setCreatedAt(now));
        List<Server> created = serverService.batchCreate(servers);
        return ResponseEntity.ok(created);
    }
    
    @Operation(summary = "批量删除服务器", description = "根据ID列表批量删除服务器")
    @DeleteMapping("/batch")
    public ResponseEntity<String> batchDelete(@RequestBody List<Long> ids) {
        serverService.batchDelete(ids);
        return ResponseEntity.ok("批量删除成功，共删除 " + ids.size() + " 个服务器");
    }
    
    @Operation(summary = "批量更新服务器状态", description = "批量更新多个服务器的状态")
    @PatchMapping("/batch/status")
    public ResponseEntity<String> batchUpdateStatus(
            @RequestBody List<Long> ids,
            @Parameter(description = "目标状态", required = true) @RequestParam ServerStatus status) {
        serverService.batchUpdateStatus(ids, status);
        return ResponseEntity.ok("批量更新成功，共更新 " + ids.size() + " 个服务器状态为 " + status);
    }
    
    @Operation(summary = "获取服务器统计信息", description = "获取服务器数量、状态分布等统计信息")
    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics() {
        return ResponseEntity.ok(serverService.getStatistics());
    }
    
    @Operation(summary = "搜索服务器", description = "根据主机名或IP地址搜索服务器")
    @GetMapping("/search")
    public ResponseEntity<List<Server>> search(
            @Parameter(description = "搜索关键词", required = true) @RequestParam String keyword) {
        List<Server> servers = serverService.searchByKeyword(keyword);
        return ResponseEntity.ok(servers);
    }
}

